package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

    public void destroy() {
        // 在此添加过滤器销毁时的操作
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        // 获取需要的 request,response,session 对象
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 获取用户请求的 URI
        String path = request.getRequestURI();
        HttpSession session = request.getSession(false); // 获取会话，但不创建新的会话
        String userName = null;
        if (session!= null) {
            userName = (String) session.getAttribute("username");
        }
        // 登录和注册页面直接放行
        if (path.indexOf("/login.jsp") > -1 || path.indexOf("/register.jsp") > -1) {
            chain.doFilter(request, response);
            return;
        }
        // 判断用户是否获取到登录信息，若未获取到或用户名错误则重定向到登录页面
        if (userName == null || "".equals(userName) || "invalidUsername".equals(userName)) {
            // 使用 getContextPath 拼接重定向路径，提高灵活性
            response.sendRedirect(request.getContextPath() + "/login/login.jsp");
        } else {
            // 已登录，继续后续处理
            chain.doFilter(request, response);
        }
    }

    public void init(FilterConfig arg0) throws ServletException {
        // 在此添加过滤器初始化时的操作
    }
}